from typing import List, Optional, Dict
from fastapi import APIRouter, HTTPException, Query, BackgroundTasks
from datetime import datetime

from app.models.hot import HotResponse, PlatformsResponse, ErrorResponse, PlatformInfo
from app.services.hot_data_service import hot_data_service
from app.core.config import settings



router = APIRouter(prefix="/hot", tags=["hot"])


@router.get("/platforms", response_model=PlatformsResponse)
async def get_platforms():
    """
    获取所有可用的平台列表
    
    返回支持的所有热点平台信息
    """
    async with hot_data_service as service:
        platforms = await service.get_platforms_info()
    
    # 将字典格式转换为PlatformInfo列表
    platform_list = [
        PlatformInfo(
            name=key,
            platform_name=value["name"],
            type=value["type"],
            description=value.get("description", ""),
            available=True
        )
        for key, value in platforms.items()
    ]
        
    return PlatformsResponse(
        platforms=platform_list,
        count=len(platform_list),
        updated_at=datetime.now()
    )


@router.get("/{platform}", response_model=HotResponse)
async def get_platform_hot(
    platform: str,
    limit: Optional[int] = Query(20, ge=1, le=100, description="返回数据条数限制")
):
    """
    获取指定平台的热点数据
    
    - **platform**: 平台标识符，如 zhihu、bilibili、weibo 等
    - **limit**: 返回数据条数限制，默认20条，最大100条
    - **cache**: 是否使用缓存，默认开启
    """
    # 验证平台是否支持
    from app.core.hot.platforms import platform_config
    if platform not in platform_config.get_available_platforms():
        raise HTTPException(
            status_code=404,
            detail=ErrorResponse(
                code=404,
                error="Platform not found",
                message=f"平台 '{platform}' 暂不支持",
                detail=f"支持的平台: {list(platform_config.get_available_platforms().keys())}"
            ).dict()
        )
        
    try:
        async with hot_data_service as service:
            result = await service.fetch_platform_data(platform)
            
        if not result:
            raise HTTPException(
                status_code=503,
                detail=ErrorResponse(
                    code=503,
                    error="Service unavailable",
                    message=f"无法获取 {platform} 的热点数据",
                    detail="请稍后重试或检查网络连接"
                ).dict()
            )
        
        # 应用limit限制
        if limit < len(result.data):
            result.data = result.data[:limit]
        
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=ErrorResponse(
                code=500,
                error="Internal server error",
                message=f"获取 {platform} 数据时发生错误",
                detail=str(e)
            ).dict()
        )


@router.get("", response_model=Dict[str, HotResponse])
async def get_all_platforms_hot(
    platforms: Optional[List[str]] = Query(None, description="指定平台列表，不指定则获取所有"),
    limit: Optional[int] = Query(10, ge=1, le=50, description="每个平台返回数据条数限制"),
    background_tasks: BackgroundTasks = BackgroundTasks()
):
    """
    批量获取多个平台的热点数据
    
    - **platforms**: 平台列表，如 ['zhihu', 'bilibili']，不指定则获取所有平台
    - **limit**: 每个平台返回数据条数限制，默认10条
    """
    from app.core.hot.platforms import platform_config
    
    # 验证平台列表
    available_platforms = set(platform_config.get_available_platforms().keys())
    if platforms:
        invalid_platforms = set(platforms) - available_platforms
        if invalid_platforms:
            raise HTTPException(
                status_code=400,
                detail=ErrorResponse(
                    code=400,
                    error="Invalid platforms",
                    message=f"以下平台暂不支持: {list(invalid_platforms)}",
                    detail=f"支持的平台: {list(available_platforms)}"
                ).dict()
            )
        target_platforms = platforms
    else:
        target_platforms = list(available_platforms)
    
    try:
        async with hot_data_service as service:
            # 并发获取所有平台数据
            results = await service.fetch_all_platforms()
        
        # 应用limit限制并过滤None结果
        filtered_results = {}
        for platform, result in results.items():
            if result and platform in target_platforms:
                if limit < len(result.data):
                    result.data = result.data[:limit]
                filtered_results[platform] = result
        
        return filtered_results
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=ErrorResponse(
                code=500,
                error="Internal server error",
                message="批量获取数据时发生错误",
                detail=str(e)
            ).dict()
        )


@router.post("/refresh/{platform}")
async def refresh_platform_cache(
    platform: str,
    background_tasks: BackgroundTasks = BackgroundTasks()
):
    """
    刷新指定平台的缓存数据
    
    - **platform**: 平台标识符
    """
    from app.core.hot.platforms import platform_config
    
    if platform not in platform_config.get_available_platforms():
        raise HTTPException(
            status_code=404,
            detail=ErrorResponse(
                code=404,
                error="Platform not found",
                message=f"平台 '{platform}' 暂不支持",
                detail=f"支持的平台: {list(platform_config.get_available_platforms().keys())}"
            ).dict()
        )
        
    try:
        # 后台重新获取数据
        async def refresh_data():
            async with hot_data_service as service:
                await service.fetch_platform_data(platform)
        
        background_tasks.add_task(refresh_data)
        
        return {"message": f"正在刷新 {platform} 的数据"}
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=ErrorResponse(
                code=500,
                error="Internal server error",
                message="刷新缓存时发生错误",
                detail=str(e)
            ).dict()
        )


@router.post("/refresh")
async def refresh_all_cache(
    background_tasks: BackgroundTasks = BackgroundTasks()
):
    """
    刷新所有平台的数据
    """
    try:
        from app.core.hot.platforms import platform_config
        platforms = platform_config.get_available_platforms()
        
        # 后台重新获取所有数据
        async def refresh_all():
            async with hot_data_service as service:
                await service.fetch_all_platforms()
        
        background_tasks.add_task(refresh_all)
        
        return {"message": "正在刷新所有平台的数据"}
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=ErrorResponse(
                code=500,
                error="Internal server error",
                message="刷新缓存时发生错误",
                detail=str(e)
            ).dict()
        )